home *** CD-ROM | disk | FTP | other *** search
/ Skunkware 5 / Skunkware 5.iso / src / Tools / MotifApp / Extras / TicTacToe / MoveGenerator.C < prev    next >
Encoding:
C/C++ Source or Header  |  1995-05-03  |  2.2 KB  |  78 lines

  1. ///////////////////////////////////////////////////////////////////////////////
  2. //////////////////////////////////////////////////////////////////////////////
  3. //         This example code is from the book:
  4. //
  5. //           Object-Oriented Programming with C++ and OSF/Motif
  6. //         by
  7. //           Douglas Young
  8. //           Prentice Hall, 1992
  9. //           ISBN 0-13-630252-1    
  10. //
  11. //         Copyright 1991 by Prentice Hall
  12. //         All Rights Reserved
  13. //
  14. //  Permission to use, copy, modify, and distribute this software for 
  15. //  any purpose except publication and without fee is hereby granted, provided 
  16. //  that the above copyright notice appear in all copies of the software.
  17. ///////////////////////////////////////////////////////////////////////////////
  18. //////////////////////////////////////////////////////////////////////////////
  19.  
  20.  
  21. ////////////////////////////////////////////////////
  22. // MoveGenerator.C
  23. //////////////////////////////////////////////////////
  24. #include "MoveGenerator.h"
  25. #include "Board.h"
  26. #include "unistd.h"
  27. #include "math.h"
  28.  
  29. #define CENTER 4
  30.  
  31. MoveGenerator::MoveGenerator()
  32. {
  33.     srand48 ( ( long ) getpid() );
  34. }
  35.  
  36. // A smarter move generator function that uses a one-move look-ahead
  37. // to choose moves. Algorithm is:
  38. //
  39. //     If the game can win in one move, it does so.
  40. //     Else If the user can win in one move, block the move
  41. //     Else If the center square is open, grab it
  42. //     Else pick a random move from those available
  43.  
  44. int MoveGenerator::getNextMove ( Board *board )
  45. {
  46.     int randomIndex, movesLeft, nextMove;
  47.     
  48.     // Get the list of free squares on the Board
  49.     
  50.     int * const freeSquares = board->freeSquares ( movesLeft );
  51.  
  52.     // If center is free, grab it.
  53.  
  54.     if ( movesLeft == 0 )
  55.     return -1;
  56.  
  57.     // See if we can win with this move
  58.  
  59.     if( ( nextMove = board->winningMove ( OO ) ) > 0 )
  60.     return nextMove;
  61.  
  62.     // Check if user is about to win
  63.  
  64.     if( ( nextMove = board->winningMove ( XX ) ) > 0 )
  65.     return nextMove;
  66.  
  67.     // Grab the middle 
  68.  
  69.     if( board->value ( CENTER ) == NOBODYYET )
  70.     return CENTER;
  71.     
  72.     // Pick one of the free squares at random and return it
  73.     
  74.     randomIndex = ( int ) ( movesLeft * drand48() );
  75.     
  76.     return freeSquares[randomIndex];
  77. }
  78.